//
//  EditJobInfoService.swift
//  ezyform
//
//  Created by Moennig Q on 9/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
import Alamofire
class EditJobInfoService: BaseService {
    func updateOwnerInfo(_ model: EditOwnerInfomationViewModel){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.UpdateOwnerInfoAPI)
        
        var params : Parameters = Parameters()
        //
        params["pvd_id"] = JobDetailModelHelper.shared.jobDetailModel.id
        params["property_type"] = model.property_type.rawValue
        params["owner_type"] = model.owner_type.rawValue
        if model.owner_type == OwnerType.individual {//individual
            params["first_name"] = model.first_name
            params["last_name"] = model.surname
            //co owner name
            if JobDetailModelHelper.shared.jobDetailModel.solar_water_heater == false{
                params["co_owner_first_name"] = model.co_owner_first_name
                params["co_owner_last_name"] = model.co_owner_surname
                params["co_owner_relation_ship"] = model.co_owner_relation_ship
            }
        }else{//other owner type
            params["first_name"] = model.company_name
            params["home_owner_abn"] = model.home_owner_abn
            params["owner_representative_name"] = model.owner_representative_name
            params["owner_representative_position"] = model.owner_representative_position
            //owner stc unit price
            params["price_to_the_home_owner"] = model.price_to_the_home_owner
            
        }
        params["gst"] = "\(model.gst)"
        params["mobile"] = model.mobile
        params["email"] = model.email
        
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            if let responseData = obj as? [String : Any], let data = PVDDetailModel.deserialize(from: responseData){
                JobDetailModelHelper.shared.jobDetailModel.owner_address = data.owner_address
                JobDetailModelHelper.shared.jobDetailModel.install_address = data.install_address
                JobDetailModelHelper.shared.jobDetailModel.gst = data.gst
                self.returnBlock(obj, nil)
            }else{
                self.errorBlock?("", "Convert response to PVDDetailModel faild")
            }
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func getCompanyNameByABN(_ abnStr: String){
        
        var urlString : String = APIConfig.getRequestAPIForV2(APIConfig.GetCompanyNameByABNAPI) + "?abn=" + abnStr
        
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let alRequest = ALRequest.init(mainURL: urlString, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    
    func updateSystemInfo(panelList: [InstallationDetailSystemDetailForPanelModel]? = nil, inverterList: [InstallationDetailSystemDetailForInverterModel]? = nil, batteryList: [InstallationDetailSystemDetailForBatteryModel]? = nil,heaterList: [InstallationDetailSystemDetailForHeaterModel]? = nil, haveBattery: Bool? = nil, spvCheck: Bool){
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UpdateSystemInfoAPI)
        netmanagerForUpload.upload(multipartFormData: {(formData) in
            
            //panel
            if let list = panelList{
                var paramsList = [UploadPanelModel]()
                for data in list {
                    var newModel = UploadPanelModel()
                    newModel.pvd_system_panel_id = data.id
                    newModel.panel_id = data.panel_brand_id
                    newModel.watts = data.watts_per_panel
                    newModel.qty = data.number_panels
                    newModel.deleted_at = (data.deleted_at ? "true" : "false")
                    paramsList.append(newModel)
                }
                
                if let data = try?  JSONSerialization.data(withJSONObject: paramsList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted){
                    formData.append(data, withName: "panels")
                }
            }
            //inverter
            if let list = inverterList{
                var paramsList = [UploadInverterModel]()
                for data in list {
                    var newModel = UploadInverterModel()
                    newModel.pvd_system_inverter_id = data.id
                    newModel.inverter_id = data.inverter_brand_id
                    newModel.qty = data.number_inverters
                    newModel.deleted_at = (data.deleted_at ? "true" : "false")
                    paramsList.append(newModel)
                }

                if let data = try?  JSONSerialization.data(withJSONObject: paramsList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted){
                    formData.append(data, withName: "inverters")
                }
            }
            //inverter
            if let list = batteryList, let isBattery = haveBattery{
                if isBattery {//有电池
                    var paramsList = [UploadBatteryModel]()
                    for data in list {
                        var newModel = UploadBatteryModel()
                        newModel.pvd_system_battery_id = data.id
                        newModel.battery_id = data.battery_storage_id
                        newModel.qty = data.number_batteries
                        let partOfAggresFlag = data.battery_system_part_of_an_aggregated_control
                        let changeBatteryFlag = data.changed_the_default_battery_manufacturer_setting
                        newModel.changed_the_default_battery_manufacturer_setting = (changeBatteryFlag ? "true": "false")
                        newModel.battery_system_part_of_an_aggregated_control = (partOfAggresFlag ? "true": "false")
                        newModel.deleted_at = (data.deleted_at ? "true" : "false")
                        paramsList.append(newModel)
                    }
                    if let data = try?  JSONSerialization.data(withJSONObject: paramsList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted){
                        formData.append(data, withName: "batteries")
                    }
                }
                //isbattery
                let isBatterString = isBattery ? "true" : "false"
                formData.append(isBatterString.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "is_battery")
                
            }
            //tank
            if let list =  heaterList{
                var paramsList = [UploadTankModel]()
                for data in list {
                    var newModel = UploadTankModel()
                    newModel.pvd_system_heater_id = data.id
                    newModel.heater_id = data.heater_brand_id
                    newModel.qty = Int64(data.number_heaters)
                    newModel.deleted_at = (data.deleted_at ? "true" : "false")
                    paramsList.append(newModel)
                }
                if list.count > 0{
                    let isSecondHandFlag = list[0].second_hand_flg  ? "true" : "false"
                    let isMoreThanOneFlag = list[0].multi_heater_flg  ? "true" : "false"
                    formData.append(isSecondHandFlag.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "second_hand_flg")
                    formData.append(isMoreThanOneFlag.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "multi_heater_flg")
                }
                if let data = try?  JSONSerialization.data(withJSONObject: paramsList.toJSON(), options: JSONSerialization.WritingOptions.prettyPrinted){
                    formData.append(data, withName: "heaters")
                    
                }
            }
            //是否开启spv
            let spvCheckString = spvCheck ? "true" : "false"
            formData.append(spvCheckString.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "spv_check")
            formData.append(JobDetailModelHelper.shared.jobDetailModel.id.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: "pvd_id")
        }, to: urlStr, method: HTTPMethod.post, headers: RequestConstant.AuthTokenParam).responseData { resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag{
                            if let responseData = dic.object(forKey: "data") as? [String: Any],  let data = PVDDetailModel.deserialize(from: responseData){
                                self.returnBlock(data,nil)
                            }else{
                                self.errorBlock("","convert responseData  to PVDDetailModel failed")
                            }
                        }else{
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(APIConfig.UpdateSystemInfoAPI)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                    // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding
                    // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it
//                    print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))")
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    func updateInstallationType(_ systemInfo: InstallationTypeViewModel){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.UpdateInstallationTypeAPI)
        
        var params : Parameters = Parameters()
        params["pvd_id"] = systemInfo.pvd_id
        params["installation_type"] = systemInfo.installation_type_value
        params["additional_capacity_details"] = systemInfo.additional_upgrade_system_details
        
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            if let responseData = obj as? [String: Any],  let data = PVDDetailModel.deserialize(from: responseData){
                JobDetailModelHelper.shared.jobDetailModel.system_detail = data.system_detail
                self.returnBlock(data,nil)
            }else{
                self.errorBlock("","convert responseData  to PVDDetailModel failed")
            }
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func updateGridConnected(_ systemInfo: GridConnectedViewModel){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.UpdateConnectedTypeAPI)
        
        var params : Parameters = Parameters()
        
        params["pvd_id"] = systemInfo.pvd_id
        params["connected_type"] = systemInfo.connected_type.rawValue
        params["nmi"] = systemInfo.nmi
        params["grid_connection_application_ref_no"] = systemInfo.gridConnectionApplicationRefNo
        let alRequest = ALRequest.init(mainURL: url, method: .post, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj, _) -> Void in
            if let responseData = obj as? [String: Any],  let data = PVDDetailModel.deserialize(from: responseData){
                self.returnBlock(data,nil)
            }else{
                self.errorBlock("","convert responseData  to PVDDetailModel failed")
            }
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    func getAdditionalInfomationTipHtmlInfo(){
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.GetPopOverTitleAPI + "type=additional_information")
        
        let alRequest = ALRequest.init(mainURL: url, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            self.returnBlock(obj, nil)
        }){(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
}
